import { defineStore } from "pinia";
import { authApi } from "@/api/user/auth";

export const useUserStore = defineStore("user", {
    state: () => ({
        // 用户信息
        userInfo: null,
        // 访问令牌
        accessToken: localStorage.getItem('accessToken') || '',
        // 刷新令牌
        refreshToken: localStorage.getItem('refreshToken') || '',
        // 是否已登录
        isLoggedIn: false,
        // token刷新中标志
        isRefreshing: false,
        // 等待token刷新的请求队列
        refreshQueue: []
    }),

    getters: {
        // 获取用户名
        username: (state) => state.userInfo?.userName || '',
        // 获取头像
        avatar: (state) => state.userInfo?.avatarUrl || '',
        // 是否已认证
        isAuthenticated: (state) => !!state.accessToken && !!state.userInfo
    },

    actions: {
        /**
         * 登录
         */
        async login(loginData) {
            try {
                const response = await authApi.login(loginData);

                // 保存token和用户信息
                this.accessToken = response.accessToken;
                this.refreshToken = response.refreshToken;
                this.userInfo = {
                    userName: response.userName,
                    avatarUrl: response.avatarUrl,
                    userId: response.userId
                };
                this.isLoggedIn = true;

                // 持久化存储
                localStorage.setItem('accessToken', this.accessToken);
                localStorage.setItem('refreshToken', this.refreshToken);
                localStorage.setItem('userInfo', JSON.stringify(this.userInfo));

                return { success: true, message: '登录成功' };
            } catch (error) {
                return {
                    success: false,
                    message: error.message || '登录失败，请重试'
                };
            }
        },

        /**
         * 注册
         */
        async register(registerData) {
            try {
                await authApi.register(registerData);
                return { success: true, message: '注册成功' };
            } catch (error) {
                return {
                    success: false,
                    message: error.message || '注册失败，请重试'
                };
            }
        },

        /**
         * 登出
         */
        async logout() {
            try {
                // 调用API登出
                authApi.logout();

                // 清除状态
                this.userInfo = null;
                this.accessToken = '';
                this.refreshToken = '';
                this.isLoggedIn = false;

                return { success: true, message: '已退出登录' };
            } catch (error) {
                // 即使API调用失败，也要清除本地状态
                this.userInfo = null;
                this.accessToken = '';
                this.refreshToken = '';
                this.isLoggedIn = false;

                return { success: true, message: '已退出登录' };
            }
        },

        /**
         * 刷新Token
         */
        async refreshAccessToken() {
            // 防止并发刷新
            if (this.isRefreshing) {
                return new Promise((resolve) => {
                    this.refreshQueue.push(resolve);
                });
            }

            if (!this.refreshToken) {
                this.logout();
                return Promise.reject('没有刷新令牌');
            }

            this.isRefreshing = true;

            try {
                const response = await authApi.refreshToken(this.refreshToken);

                // 更新token
                this.accessToken = response.accessToken;
                this.refreshToken = response.refreshToken;

                // 更新本地存储
                localStorage.setItem('accessToken', this.accessToken);
                localStorage.setItem('refreshToken', this.refreshToken);

                // 执行队列中等待的请求
                this.refreshQueue.forEach(resolve => resolve(this.accessToken));
                this.refreshQueue = [];

                return this.accessToken;
            } catch (error) {
                // 刷新失败，清除认证状态
                this.logout();
                this.refreshQueue.forEach(resolve => resolve(null));
                this.refreshQueue = [];

                return Promise.reject(error);
            } finally {
                this.isRefreshing = false;
            }
        },

        /**
         * 初始化用户状态（应用启动时调用）
         */
        initUserState() {
            const token = localStorage.getItem('accessToken');
            const userInfo = localStorage.getItem('userInfo');

            if (token && userInfo) {
                this.accessToken = token;
                this.userInfo = JSON.parse(userInfo);
                this.isLoggedIn = true;
            }
        },

        /**
         * 检查token有效性
         */
        checkTokenValid() {
            return !!this.accessToken;
        }
    },

    persist: {
        key: 'user-store',
        storage: localStorage,
        paths: ['userInfo', 'isLoggedIn']
    }
});